﻿//AcademicPlanner - course registration planning web app.
//Copyright (C) 2009  Boubacar Diallo

//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Routing;
using AcademicPlanner.Framework.Libraries.Mvc;
using AcademicPlanner.Framework.Helpers;
using AcademicPlanner.Domain;

namespace AcademicPlanner.Presentation
{
	/// <summary>
	/// AcademicPlannerWebApp is the AcademicPlanner application's web front end.
	/// An <code>AcademicPlannerWebApp</code> object is created and launched by the current
	/// <code>HttpHandler</code> (specified in config file). It basically registers the different
	/// web routes when the application is started before continuing execution.
	/// </summary>
	/// <since>1.0</since>
    public class AcademicPlannerWebApp : System.Web.HttpApplication
    {
		private static AcademicPlannerWebApp current;

		private readonly string appName = "AcademicPlanner";

		private string appVersion;

		private string appFullName;

		private string appOwnerName;


		/// <summary>
		/// Gets the current (latest started) <code>AcademicPlannerWebApp</code> object.
		/// </summary>
		/// <since>1.0</since>
		public static AcademicPlannerWebApp Current { get { return current; } }

		/// <summary>
		/// Gets the instance of the <see cref="T:AcademicPlanner.Domain.DomainMaster">
		/// <code>DomainMaster</code></see> singleton.
		/// </summary>
		/// <seealso cref="T:AcademicPlanner.Domain.DomainMaster" />
		/// <since>1.0</since>
		public DomainMaster DomainMaster { get { return DomainMaster.GetInstance(); } }

		/// <summary>
		/// Gets the simple name of the application.
		/// </summary>
		/// <since>1.0</since>
		public string AppName { get { return appName; } }

		/// <summary>
		/// Gets the version of the application.
		/// </summary>
		/// <since>1.0</since>
		public string AppVersion { get { return appVersion; } }

		/// <summary>
		/// Gets the complete name of the application including its complete version.
		/// </summary>
		/// <since>1.0</since>
		public string AppFullName { get { return appFullName; } }

		/// <summary>
		/// Gets the name of the owner of the application.
		/// </summary>
		/// <since>1.0</since>
		public string AppOwnerName { get { return appOwnerName; } }


        private void RegisterRoutes()
        {
			var vBaseUri = (string)ConfigHelper.GetPresentationSectionValue("urlSettings", "baseUri");
			var vBasePath = !string.IsNullOrEmpty(vBaseUri) ? vBaseUri.Substring(1) + "/default.aspx/" : "";
			
            RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


			RouteTable.Routes.MapRoute("Home", vBasePath,
										new { controller = "Site", action = "Default" });

			// /People/*

			RouteTable.Routes.MapRoute("CompletePersonRegistration", 
					vBasePath + "People/CompleteRegistration/{pFromEmail}/{pToken}/{pPersonId}",
					new { controller = "People", action = "CompleteRegistration", 
							pFromEmail = "", pToken = "", pPersonId = -1 });

			//RouteTable.Routes.MapRoute("SetupPerson",
			//                            "People/Setup/{pPersonId}",
			//                            new { controller = "People", action = "Setup", pPersonId = -1 });

			//RouteTable.Routes.MapRoute("SavePerson",
			//                            "People/Save/{pPersonId}",
			//                            new { controller = "People", action = "Save", pPersonId = -1 });


			// /Accounts/*

			RouteTable.Routes.MapRoute("RecoverAccount",
					vBasePath + "Accounts/Recover/{pFromEmail}/{pToken}/{pPersonId}",
					new
					{
						controller = "Accounts",
						action = "Recover",
						pFromEmail = "",
						pToken = "",
						pPersonId = -1
					});

			//RouteTable.Routes.MapRoute("ResetAccount",
			//                            "Accounts/Reset/{pPersonId}",
			//                            new { controller = "Accounts", action = "Reset", pPersonId = -1 });

			//RouteTable.Routes.MapRoute("SaveAccount",
			//                            "Accounts/Save/{pAccountId}",
			//                            new { controller = "Accounts", action = "Save", pAccountId = -1 });


			// /Controls/*

			RouteTable.Routes.MapRoute("AcademicPlanForm",
					vBasePath + "Controls/AcademicPlanForm/{pScenario}/{pAcademicPlanId}/{pIncludeCancelButton}/{pHtmlId}",
					new
					{
						controller = "Controls",
						action = "AcademicPlanForm",
						pScenario = "",
						pAcademicPlanId = -1,
						pIncludeCancelButton = true,
						pHtmlId = ""
					});

			RouteTable.Routes.MapRoute("AcademicPlanControl",
					vBasePath + "Controls/AcademicPlanControl/{pAcademicPlanId}/{pHtmlId}",
					new
					{
						controller = "Controls",
						action = "AcademicPlanControl",
						pAcademicPlanId = -1,
						pHtmlId = ""
					});

			RouteTable.Routes.MapRoute("CourseForm",
					vBasePath + "Controls/CourseForm/{pScenario}/{pCourseId}/{pPlanId}",
					new
					{
						controller = "Controls",
						action = "CourseForm",
						pCourseId = -1,
						pPlanId = -1
					});

			RouteTable.Routes.MapRoute("ProgramForm",
					vBasePath + "Controls/ProgramForm/{pScenario}/{pProgramId}/{pPlanId}",
					new
					{
						controller = "Controls",
						action = "ProgramForm",
						pScenario = "",
						pProgramId = -1,
						pPlanId = -1
					});

			RouteTable.Routes.MapRoute("AcademicScheduleForm",
					vBasePath + "Controls/AcademicScheduleForm/{pScenario}/{pAcademicScheduleId}/{pPlanId}",
					new
					{
						controller = "Controls",
						action = "AcademicScheduleForm",
						pAcademicScheduleId = -1,
						pPlanId = -1
					});

			RouteTable.Routes.MapRoute("AcademicScheduleControl",
					vBasePath + "Controls/AcademicScheduleControl/{pAcademicScheduleId}",
					new
					{
						controller = "Controls",
						action = "AcademicScheduleControl",
						pAcademicScheduleId = -1
					});


			// /*
			RouteTable.Routes.MapRoute("Site", vBasePath + "{action}", 
										new { controller = "Site", action = "Default" });


			// /*/Save
			RouteTable.Routes.MapRoute("SaveModel",
										vBasePath + "{controller}/Save/{pId}/{pParentId}",
										new { controller = "Programs", action = "Save", pId = -1, pParentId = -1 });


			// /*/*/<id>
			RouteTable.Routes.MapRoute("ActionOnModel", vBasePath + "{controller}/{action}/{pId}",
										new { controller = "People", action = "Save", pId = -1 });


			// /*/*
			RouteTable.Routes.MapRoute("Default", vBasePath + "{controller}/{action}", 
										new { controller = "Site", action = "Default" });
        }

		/// <summary>
		/// Handles the event to start the application.
		/// </summary>
		/// <remarks>
		/// This method registers the web routes and the sets
		/// the application's identifiers such as <see cref="P:AppFullName"/>.
		/// </remarks>
		/// <param name="sender">The sender of the event.</param>
		/// <param name="e">The details of the event.</param>
		/// <seealso cref="T:System.Web.Routing.RouteTable"/>
		/// <seealso cref="P:System.Web.Routing.RouteTable.Routes"/>
		/// <seealso cref="M:System.Web.Routing.RouteTable.Routes.MapRoute"/>
		/// <since>1.0</since>
        protected void Application_Start(object sender, EventArgs e)
        {
			current = this;
			SetAppIdentifiers();
            RegisterRoutes();
        }

		private void SetAppIdentifiers()
		{
			var vAssembly = typeof(AcademicPlannerWebApp).Assembly;
			var vVersion = vAssembly.GetName().Version;
			var vInfoVersionAttrs = vAssembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false);

			appVersion = vVersion.ToString(1);
			if (vInfoVersionAttrs.Length > 0)
			{
				appVersion = ((AssemblyInformationalVersionAttribute)vInfoVersionAttrs[0]).InformationalVersion;
			}
			appFullName = appName + "-" + appVersion +
							" (r" + vVersion.Revision.ToString() + 
							"-b" + vVersion.Build.ToString() + ")";
			appOwnerName = (string)ConfigHelper.GetDomainSectionValue("generalSettings",
													"appOwnerName");
		}

		//protected void Session_Start(object sender, EventArgs e)
		//{
			
		//}

		//protected void Application_BeginRequest(object sender, EventArgs e)
		//{
		//    var vBaseUri = (string)ConfigHelper.GetPresentationSectionValue("urlSettings", "baseUri");
		//    var vBasePath = vBaseUri + "/";

		//    if (!string.IsNullOrEmpty(vBaseUri) &&
		//        !Request.Url.IsFile && Request.Path.ToLower().StartsWith(vBasePath))
		//    {
		//        Context.RewritePath(Request.Path.Replace(vBasePath, "/"), false);
		//    }
		//}
			
		//protected void Application_AuthenticateRequest(object sender, EventArgs e)
		//{

		//}

		//protected void Application_Error(object sender, EventArgs e)
		//{
			
		//}

		//protected void Session_End(object sender, EventArgs e)
		//{

		//}

		//protected void Application_End(object sender, EventArgs e)
		//{

		//}
    }
}